'use strict';
const ms = require('ms');

module.exports = app => {
  return class FrontLoginController extends app.Controller {
    // 登录页
    async loginPage() {
      const ctx = this.ctx; 
      if(ctx.session.frontUser) {
        ctx.redirect('/');
      }
      ctx.locals = {
        page_title: '登录',
        site: app.config.site,
        bodyClass: 'signin',
        errMsg: ctx.session.errMsg
      };
      if(ctx.session.errMsg) ctx.session.errMsg = null;
      await ctx.render('front/login.html');
    }

    // 登录
    async login() {
      const ctx = this.ctx;
      if(ctx.session.frontUser) {
        ctx.redirect('/');
      }
      const body = ctx.request.body;
      if (body.remember === 'true') {
        ctx.session.maxAge = ms('30d');
      }
      const post = await ctx.service.login.post(body);
      if (post) {
        if(post.user_id) {
          ctx.session.frontUser = post;
          ctx.redirect('/');
        } else {
          ctx.locals = {
            page_title: '登录',
            site: app.config.site,
            bodyClass: 'signin',
            errMsg: post.message
          }
          await ctx.render('front/login.html');
        }
      } 
    }

    // 登出
    async logout() {
      const ctx = this.ctx;
      ctx.session.frontUser = null;
      ctx.redirect('/login');
    }
  };
};
